import {
    createAGroupFolder,
    getPlayerData,
    isGroupExist,
    isPlayerExist,
    storagePlayerData,
    deletePlayerData,
    ensureGroupAndPlayerExist,
    getConfig,
    formatCurrency,
    checkPermission
} from "../function/function.js";
import lodash from 'lodash'
import fs from 'fs';

// 读取文案配置文件
const copywriting = JSON.parse(fs.readFileSync('plugins/Slave-Market/resources/data/workCopywriting.json', 'utf-8'))

export class Sm extends plugin {
    constructor() {
        super({
            name: '[Sm]购买奴隶',
            dsc: '购买奴隶',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]购买(群友|奴隶)(\d+)?/, fnc: 'purchaseSlaves' },
                { reg: /^[#\/]重置购买冷却$/, fnc: 'resetpurchaseSlaves' },
                { reg: /^[#\/]卖身(\d+)?/, fnc: 'sellSelf' },
                { reg: /^[#\/]自愿认主(\d+)?/, fnc: 'voluntarySlavery' } // 新增功能
            ]
        })
    }

    async purchaseSlaves(e) {
        if (!e.isGroup) return e.reply(['该游戏只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        // 初始化玩家数据
        ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);

        // 获取目标奴隶ID
        let slave = e.at;
        if (!slave) slave = e.msg.replace(/#|\/|购买|群友|奴隶|\s/g, '');
        slave = parseInt(slave);

        // 禁止购买机器人
        if (slave === Bot.uin || e.atme) return e.reply(['不可以购买我捏~']);

        // 如果目标在群中，也初始化他的数据
        const memberInfo = (await Bot.pickGroup(ID[1]).getMemberMap()).get(Number(slave));
        if (memberInfo) {
            ensureGroupAndPlayerExist(ID[1], slave, memberInfo.card || memberInfo.nickname);
        }

        // 禁止购买自己
        if (slave === ID[0]) return e.reply(['不可以购买自己捏~']);

        try {
            // 获取群成员列表
            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);

            // 检查目标是否在群内
            if (!memberInfoList[slave]) return e.reply([`本群不存在[${slave}]`]);

            slave = parseInt(slave);

            // 如果目标没有游戏数据，则初始化
            if (!isPlayerExist(ID[1], slave)) {
                storagePlayerData(ID[1], slave, {
                    currency: 0,
                    slave: [],
                    value: 100,
                    lastWorkingTime: 0,
                    master: ''
                });
            }

            // 获取玩家和目标的数据
            const userData = await getPlayerData(ID[1], ID[0]);
            const slaveData = await getPlayerData(ID[1], slave);

            // 检查目标是否处于保护期内
            const currentTime = Math.floor(Date.now() / 1000);
            if (slaveData.protectionUntil && currentTime < slaveData.protectionUntil) {
                // 计算剩余保护时间
                const remainingProtection = slaveData.protectionUntil - currentTime;
                const hours = Math.floor(remainingProtection / 3600);
                const minutes = Math.floor((remainingProtection % 3600) / 60);
                
                return e.reply([
                    segment.at(ID[0]),
                    `该玩家处于赎身后的保护期内，无法购买！\n` +
                    `保护期剩余时间: ${hours}小时${minutes}分钟`
                ]);
            }

            const { currency } = userData;
            let { currency: slavecurrency, value: slavevalue, master: slaveMaster } = slaveData;
            slavevalue = Number(slavevalue.toFixed(2));

            // 检查是否已经是主人
            if (slaveMaster === ID[0]) return e.reply([
                segment.at(ID[0]),
                '你已经是他的主人了'
            ]);

            // 计算税收（如果买家已有奴隶，则需要缴纳额外税收）
            const config = getConfig();
            const taxRate = config.purchase?.taxRate || 0.1; // 默认税率10%
            const hasTax = userData.slave && userData.slave.length > 0;
            const taxAmount = hasTax ? formatCurrency(slavevalue * taxRate) : 0;
            const totalCost = formatCurrency(slavevalue + taxAmount);

            // 检查是否有足够的金币
            if (currency < totalCost) return e.reply([
                segment.at(ID[0]),
                `你买不起！需要${slavevalue}金币` + (hasTax ? `加上${taxAmount}金币的税收，总计${totalCost}金币` : '')
            ]);

            // 检查购买冷却时间
            const currentSecond = Math.floor(Date.now() / 1000);
            const purchaseCooldown = config.purchase.cooldown;

            if (!checkPermission(e) && currentSecond - (userData.lastPurchaseTime || 0) < purchaseCooldown) {
                const remainingTime = purchaseCooldown - (currentSecond - (userData.lastPurchaseTime || 0));
                return e.reply([`购买冷却中，剩余时间：${Math.floor(remainingTime / 3600)}小时${Math.floor((remainingTime % 3600) / 60)}分钟`]);
            }

            // 禁止购买自己的主人
            if (slave === userData.master) {
                return e.reply(lodash.sample(copywriting.buyMaster));
            }

            // 处理购买自由玩家的情况
            if (slaveMaster === '') {
                // 更新买家数据
                userData['currency'] = formatCurrency(userData['currency'] - totalCost);
                userData['slave'].push(slave);
                userData['lastPurchaseTime'] = currentSecond;
                storagePlayerData(ID[1], ID[0], userData);

                // 更新被购买者数据
                slaveData['currency'] = formatCurrency(slaveData['currency'] + Number(slavevalue.toFixed(2)));
                slaveData['value'] = formatCurrency(Number((slaveData['value'] + 20.00).toFixed(2)));
                slaveData['master'] = ID[0];
                storagePlayerData(ID[1], slave, slaveData);

                let reply = `成功购买了${memberInfoList[slave]['nickname']}！花费了${slavevalue.toFixed(2)}金币`;
                
                // 如果有税收，添加税收信息
                if (hasTax) {
                    reply += `和${taxAmount.toFixed(2)}金币的税收`;
                }
                
                reply += `，还剩${formatCurrency(currency - totalCost).toFixed(2)}金币\n${memberInfoList[slave]['nickname']}获得了${slavevalue.toFixed(2)}金币，现在拥有${formatCurrency(slavecurrency + slavevalue).toFixed(2)}金币，身价上涨${slavevalue.toFixed(2)}->${(slavevalue + 20.00).toFixed(2)}`;
                
                return e.reply([reply]);
            } else {
                // 处理购买他人奴隶的情况
                const formerOwnerData = await getPlayerData(ID[1], slaveMaster);

                // 更新买家数据
                userData['currency'] = formatCurrency(userData['currency'] - totalCost);
                userData['slave'].push(slave);
                userData['lastPurchaseTime'] = currentSecond;
                storagePlayerData(ID[1], ID[0], userData);

                // 更新被购买者数据
                slaveData['currency'] = formatCurrency(slaveData['currency'] + Number((slavevalue / 10).toFixed(2)));
                slaveData['value'] = formatCurrency(Number((slaveData['value'] + 20.00).toFixed(2)));
                slaveData['master'] = ID[0];
                storagePlayerData(ID[1], slave, slaveData);

                // 更新原主人数据
                formerOwnerData['currency'] = formatCurrency(formerOwnerData['currency'] + Number(slavevalue.toFixed(2)));
                formerOwnerData['slave'] = formerOwnerData['slave'].filter(a => a !== slave);
                storagePlayerData(ID[1], slaveMaster, formerOwnerData);

                // 如果原主人已不在群内，删除其数据
                if (!memberInfoList[slaveMaster]) {
                    deletePlayerData(ID[1], slaveMaster);
                    return e.reply([`${slaveMaster}已不在本群，已删除该用户存档\r已将其奴隶解放`]);
                }

                let reply = `成功从${memberInfoList[slaveMaster]['nickname']}那里购买了${memberInfoList[slave]['nickname']}！花费了${slavevalue.toFixed(2)}金币`;
                
                // 如果有税收，添加税收信息
                if (hasTax) {
                    reply += `和${taxAmount.toFixed(2)}金币的税收`;
                }
                
                reply += `，还剩${formatCurrency(currency - totalCost).toFixed(2)}金币\n${memberInfoList[slaveMaster]['nickname']}获得了${slavevalue.toFixed(2)}金币，现在拥有${formerOwnerData['currency'].toFixed(2)}金币\n${memberInfoList[slave]['nickname']}额外获得了${(slavevalue / 10).toFixed(2)}金币，现在拥有${formatCurrency(slavecurrency + slavevalue / 10).toFixed(2)}金币，身价上涨${slavevalue.toFixed(2)}->${(slavevalue + 20.00).toFixed(2)}`;
                
                return e.reply([reply]);
            }
        } catch (error) {
            logger.error('处理购买请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试。']);
        }
    }

    async sellSelf(e) {
        if (!e.isGroup) return e.reply(['该游戏只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        // 初始化玩家数据
        ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);

        // 获取目标主人ID
        let master = e.at;
        if (!master) master = e.msg.replace(/#|\/|卖身|\s/g, '');
        master = parseInt(master);

        // 禁止卖身给机器人
        if (master === Bot.uin || e.atme) return e.reply(['不可以卖身给我捏~']);

        // 禁止卖身给自己
        if (master === ID[0]) return e.reply(['不可以卖身给自己捏~']);

        try {
            // 获取群成员列表
            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);

            // 检查目标是否在群内
            if (!memberInfoList[master]) return e.reply([`本群不存在[${master}]`]);

            master = parseInt(master);

            // 初始化目标主人的数据
            if (memberInfoList[master]) {
                ensureGroupAndPlayerExist(ID[1], master, memberInfoList[master].card || memberInfoList[master].nickname);
            }

            // 获取玩家和目标主人的数据
            const userData = await getPlayerData(ID[1], ID[0]);
            const masterData = await getPlayerData(ID[1], master);

            // 检查玩家是否已经有主人
            if (userData.master !== '') return e.reply([
                segment.at(ID[0]),
                '你已经有主人了，不能再卖身给别人'
            ]);

            // 检查玩家的身价和目标主人的金币
            const userValue = Number(userData.value.toFixed(2));
            
            // 检查是否已经是对方的奴隶
            if (masterData.slave.includes(ID[0])) return e.reply([
                segment.at(ID[0]),
                '你已经是Ta的奴隶了'
            ]);

            // 检查对方是否有足够的金币
            if (masterData.currency < userValue) return e.reply([
                segment.at(ID[0]),
                `对方买不起你！你的身价为${userValue}金币，但对方只有${masterData.currency.toFixed(2)}金币`
            ]);
            
            // 检查对方是否是你的奴隶
            if (userData.slave.includes(master)) return e.reply([
                segment.at(ID[0]),
                '对方是你的奴隶，你不能卖身给自己的奴隶'
            ]);

            // 检查卖身冷却时间
            const config = getConfig();
            const currentSecond = Math.floor(Date.now() / 1000);
            const sellCooldown = config.purchase.cooldown; // 使用相同的冷却时间

            if (!checkPermission(e) && currentSecond - (userData.lastSellTime || 0) < sellCooldown) {
                const remainingTime = sellCooldown - (currentSecond - (userData.lastSellTime || 0));
                return e.reply([`卖身冷却中，剩余时间：${Math.floor(remainingTime / 3600)}小时${Math.floor((remainingTime % 3600) / 60)}分钟`]);
            }

            // 更新卖身者数据
            userData.currency = formatCurrency(userData.currency + Number(userValue.toFixed(2)));
            userData.value = formatCurrency(Number((userData.value + 20.00).toFixed(2)));
            userData.master = master;
            userData.lastSellTime = currentSecond;
            storagePlayerData(ID[1], ID[0], userData);

            // 更新买家数据
            masterData.currency = formatCurrency(masterData.currency - Number(userValue.toFixed(2)));
            masterData.slave.push(ID[0]);
            storagePlayerData(ID[1], master, masterData);

            return e.reply([
                `${e.sender.card || e.sender.nickname}成功卖身给${memberInfoList[master]['nickname']}！\n` +
                `获得了${userValue.toFixed(2)}金币，现在拥有${userData.currency.toFixed(2)}金币\n` +
                `身价上涨：${(userData.value - 20).toFixed(2)}->${userData.value.toFixed(2)}\n` +
                `${memberInfoList[master]['nickname']}消费了${userValue.toFixed(2)}金币，还剩${masterData.currency.toFixed(2)}金币`
            ]);
            
        } catch (error) {
            logger.error('处理卖身请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试。']);
        }
    }

    async resetpurchaseSlaves(e) {
        if (!e.isMaster) return e.reply('只有主人才能重置冷却时间');
        if (!e.isGroup) return e.reply('该命令只能在群内使用');

        try {
            const groupId = e.group_id;
            const files = fs.readdirSync(`plugins/Slave-Market/data/player/${groupId}`);
            
            for (const file of files) {
                if (file.endsWith('.json')) {
                    const playerData = await getPlayerData(groupId, file.replace('.json', ''));
                    playerData.lastPurchaseTime = 0;
                    storagePlayerData(groupId, file.replace('.json', ''), playerData);
                }
            }
            
            return e.reply('已重置本群所有成员的购买冷却时间');
        } catch (error) {
            logger.error('重置购买冷却时间时出错:', error);
            return e.reply('重置冷却时间时出错，请稍后再试');
        }
    }

    /**
     * 自愿认主功能
     * 无需对方付出金币，但会导致自己身价折半，损失一半财富
     * @param {*} e 消息事件
     * @returns 
     */
    async voluntarySlavery(e) {
        if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        // 初始化玩家数据
        ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);

        // 获取目标主人ID
        let master = e.at;
        if (!master) master = e.msg.replace(/#|\/|自愿认主|\s/g, '');
        master = parseInt(master);

        // 禁止认主给机器人
        if (master === Bot.uin || e.atme) return e.reply(['我不接受这种卑微的贡献~']);

        // 禁止认主给自己
        if (master === ID[0]) return e.reply(['不能认自己为主人~']);

        try {
            // 获取群成员列表
            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);

            // 检查目标是否在群内
            if (!memberInfoList[master]) return e.reply([`本群不存在[${master}]`]);

            master = parseInt(master);

            // 初始化目标主人的数据
            if (memberInfoList[master]) {
                ensureGroupAndPlayerExist(ID[1], master, memberInfoList[master].card || memberInfoList[master].nickname);
            }

            // 获取玩家和目标主人的数据
            const userData = await getPlayerData(ID[1], ID[0]);
            const masterData = await getPlayerData(ID[1], master);

            // 检查玩家是否已经有主人
            if (userData.master !== '') return e.reply([
                segment.at(ID[0]),
                '你已经有主人了，不能再认别人为主'
            ]);
            
            // 检查是否已经是对方的奴隶
            if (masterData.slave && masterData.slave.includes(ID[0])) return e.reply([
                segment.at(ID[0]),
                '你已经是Ta的奴隶了'
            ]);
            
            // 检查对方是否是你的奴隶
            if (userData.slave && userData.slave.includes(master)) return e.reply([
                segment.at(ID[0]),
                '对方是你的奴隶，你不能认自己的奴隶为主人'
            ]);

            // 确认是否真的要认主
            if (!e.msg.includes('确认')) {
                return e.reply([
                    segment.at(ID[0]),
                    `⚠️警告：自愿认主将导致你的身价折半，失去一半财富！\n` +
                    `如果你确定要认${memberInfoList[master].card || memberInfoList[master].nickname}为主人，\n` +
                    `请发送：#自愿认主${master} 确认`
                ]);
            }

            // 检查认主冷却时间
            const config = getConfig();
            const currentSecond = Math.floor(Date.now() / 1000);
            const voluntaryCooldown = config.purchase.cooldown * 2; // 使用更长的冷却时间

            if (!checkPermission(e) && currentSecond - (userData.lastVoluntaryTime || 0) < voluntaryCooldown) {
                const remainingTime = voluntaryCooldown - (currentSecond - (userData.lastVoluntaryTime || 0));
                return e.reply([`认主冷却中，剩余时间：${Math.floor(remainingTime / 3600)}小时${Math.floor((remainingTime % 3600) / 60)}分钟`]);
            }

            // 计算财富和损失
            const userCurrency = userData.currency || 0;
            const userBankSavings = userData.bankBalance || 0;
            const totalWealth = userCurrency + userBankSavings;
            
            // 计算主人获得的财富（玩家总财富的30%）
            const contributionToMaster = formatCurrency(totalWealth * 0.3);
            
            // 计算玩家剩余的财富（总财富的50%）
            const remainingWealth = formatCurrency(totalWealth * 0.5);
            
            // 计算身价折半后的新身价
            const newValue = formatCurrency(userData.value * 0.5);

            // 更新认主者数据
            userData.currency = formatCurrency(remainingWealth); // 所有剩余财富都转到余额中
            userData.bankBalance = 0; // 银行存款清零
            userData.value = newValue; // 身价折半
            userData.master = master; // 设置新主人
            userData.lastVoluntaryTime = currentSecond; // 更新认主时间
            storagePlayerData(ID[1], ID[0], userData);

            // 更新新主人数据
            masterData.currency = formatCurrency(masterData.currency + contributionToMaster); // 获得贡献财富
            if (!masterData.slave) masterData.slave = [];
            masterData.slave.push(ID[0]); // 添加新奴隶
            storagePlayerData(ID[1], master, masterData);

            // 获取名称显示
            const slaveName = e.sender.card || e.sender.nickname;
            const masterName = memberInfoList[master].card || memberInfoList[master].nickname;

            // 计算损失的财富
            const lostWealth = formatCurrency(totalWealth * 0.5);
            
            // 构建具有羞辱感的回复消息
            const replies = [
                `${slaveName}卑微地跪在${masterName}面前，宣誓效忠！`,
                `${slaveName}甘愿放弃尊严，成为${masterName}的奴仆！`,
                `${slaveName}自愿献上自己的忠诚，认${masterName}为主人！`,
                `${slaveName}低头服从于${masterName}的权威，成为其奴隶！`
            ];
            
            return e.reply([
                segment.at(ID[0]), "\n",
                lodash.sample(replies), "\n\n",
                `【损失结果】\n` +
                `• 身价从${userData.value + newValue}降至${newValue}金币（-50%）\n` +
                `• 贡献给主人${contributionToMaster}金币（总财富的30%）\n` +
                `• 自身损失${lostWealth}金币（总财富的50%）\n` +
                `• 剩余财富：${remainingWealth}金币\n\n` +
                `${masterName}获得了新的奴隶和${contributionToMaster}金币！`
            ]);
            
        } catch (error) {
            logger.error('处理自愿认主请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试。']);
        }
    }
}
